package com.ayi.dao.cartdao;
import com.ayi.utils.GetConn;
import java.sql.Connection;
import java.util.Map;

import static com.ayi.constants.BookShopConstants.ConstantMethods.executeSqlUpdateCartList;
import static com.ayi.constants.BookShopConstants.ConstantMethods.getEndAndStartIndexInCartList;


/**
 * @author Ayingzz
 * @create 2021/11/28 14:59
 */
public class UpdateCart {

    /**
     * 更新一本书在订单里的数量
     * @param username
     * @param id
     * @param num
     * @return
     */
    public boolean updateBookNumFromCart(String username, int id, int num) {
        Connection conn = new GetConn().getConnection();

        StringBuilder sb = new QueryCart().queryCartWithCreateAStringBuilderByUsername(username);
        int[] indexMap = getEndAndStartIndexInCartList(sb, id);
        int end = indexMap[0];
        int start = indexMap[1];

        String left = sb.substring(0, end);
        String right = sb.substring(start, sb.length());
        String middleNum = sb.substring(end, start);

        int finshNum = Integer.parseInt(middleNum) + num;

        StringBuilder finshStr = new StringBuilder();
        finshStr.append(left);
        finshStr.append(finshNum);
        finshStr.append(right);

        String sql = "update carts set cartList = ? where username = ?";

        return executeSqlUpdateCartList(username, conn, finshStr, sql);
    }
}
